<?
include_once "fbmain.php";
include_once "common_functions.php";
include_once "configuration.php";

ob_start();
system("/bin/date");
echo("<html><head></head><body>");


$dir_tmp = ($_GET['dir_tmp']);
$dir_check = ($_GET['dir_check']);
$dir_final = ($_GET['dir_final']);
$dir_final_log = $_GET['dir_final_log'];
$dir_video = ($_GET['dir_video']);
$prefix_dir = ($_GET['prefix_dir']);
$myFile_faces = ($_GET['file_faces']);
$myFile_faces_present = ($_GET['file_faces_present']);
$filepath = $_GET['file'];


$fh = fopen($myFile_faces, 'r');
$theData = fread($fh, filesize($myFile_faces));
fclose($fh);
//echo $theData;

$new_face = json_decode($theData, true);
//echo(count((array)$new_face));
//print_r($new_face);

$fh = fopen($myFile_faces_present, 'r');
$theData = fread($fh, filesize($myFile_faces_present));
fclose($fh);
//echo $theData;

$new_face_present = json_decode($theData, true);
//print_r($new_face_present);


$photos_saved_in_file = load_tabbed_file($filepath);
//print_r($photos_saved_in_file);
//echo(count($photos_saved_in_file));
//print_r($photos_saved_in_file[1][1]);
for ($fo=0;$fo<count($photos_saved_in_file);$fo++){
	//$photos_for_recognizer[$fo] = $photos_saved_in_file[$fo][1];
	$photos_for_recognizer_x[$fo] = $photos_saved_in_file[$fo][2];
	$photos_for_recognizer_y[$fo] = $photos_saved_in_file[$fo][3];
	//$counter[$fo] = $photos_saved_in_file[$fo][0];
}



//
// make a collage of the photos. 
//
//if ($do_create_collage){
if (1){

	$starttime_create_collage = compute_time();

	//	$rv = 
	create_collage($put_scr, $fbme, $dir_tmp, $prefix_dir, $dir_check, $new_face, $new_face_present, $photos_for_recognizer_x, $photos_for_recognizer_y, $dir_final, $do_check_images, $polaroid_var, $setup_scale_factor);
	//	$number_photo[3] = rv[1];   ////$rv[1] = $nmb_images_output;
	//	$number_faces = rv[0];   ////$rv[0] = $number_faces_checked;

	$number_photo[3] = 1;
	$number_faces = 1;

	$endtime_create_collage = compute_time();
}

$totaltime_create_collage = ($endtime_create_collage - $starttime_create_collage);


//
// create the video with the pictures elaborated 
//
if ($do_create_video){

	$starttime_create_video = compute_time();

	create_video($dir_final, $dir_video, $prefix_dir, $fbme, $put_scr, $setup_dir);

	$endtime_create_video = compute_time();
}

$totaltime_create_video = ($endtime_create_video - $starttime_create_video);




// write time information to file
$file_info_time = $dir_final_log."step3-create_collage.txt";
$fid_time = fopen($file_info_time, 'w') or die("can't open file");
fwrite($fid_time, $starttime_create_collage."\t".$endtime_create_collage."\t".$totaltime_create_collage."\t");
fclose($fid_time);
$file_info_time = $dir_final_log."step4-create_video.txt";
$fid_time = fopen($file_info_time, 'w') or die("can't open file");
fwrite($fid_time, $starttime_create_video."\t".$endtime_create_video."\t".$totaltime_create_video."\t");
fclose($fid_time);




//write any output to a file to check 
echo("</body></html>");
$c=ob_get_contents();
ob_end_clean();
$fp=fopen($dir_final_log."03_04_render_video.html", "wb");
fwrite($fp, $c);
fclose($fp);


//send back data for next steps
echo("log_file=".$dir_final_log."&final_video=/facecontest/code/".$dir_video."video_encoded.mpeg");





function create_video($dir_final, $dir_video, $prefix_dir, $me, $put_scr, $setup_dir){
$put_scr=true;

	if ($put_scr==true) echo("<br>");
	$command = "cd ".$setup_dir."/".$dir_final;
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outa);
	if ($put_scr==true) print_r($outa);
	if ($put_scr==true) echo("<br><br>");

	// prepare the pictures for the video
	$command = "dir2slideshow -n 'video' -t 3 -c 1 ".$setup_dir."/".$dir_final;
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outb);
	if ($put_scr==true) print_r($outb);
	if ($put_scr==true) echo("<br><br>");
	
	
	// I don't know why the video.txt is not stored in the actual directory, but in the setup_dir. So i move it back
	// take care of different users!!!!
	$command = "mv ".$setup_dir."/video.txt ".$setup_dir."/".$dir_final;
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outmove);
	if ($put_scr==true) print_r($outmove);
	if ($put_scr==true) echo("<br><br>");
	
	// create fake file, otherwise it does not work
	$command = "touch ".$setup_dir."/".$dir_video."output_video.ogg";
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outc);
	if ($put_scr==true)print_r($outc);
	if ($put_scr==true) echo("<br><br>");

	// create the video
	$command = "/usr/bin/dvd-slideshow -n 'video_vob' -f ".$setup_dir."/".$dir_final."video.txt -a '".$setup_dir."/".$dir_video."output_video.ogg'";
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outd);
	if ($put_scr==true) print_r($outd);
	if ($put_scr==true) echo("<br><br>");
	
	// I don't know why the video.txt is not stored in the actual directory, but in the setup_dir. So i move it back
	// take care of different users!!!!
	$command = "mv ".$setup_dir."/video.txt ".$setup_dir."/".$dir_final;
	if ($put_scr==true) echo($command."<br>");
	exec($command,$outmove);
	if ($put_scr==true) print_r($outmove);
	if ($put_scr==true) echo("<br><br>");

	echo(" ");
	$command = "mv ".$setup_dir."/video*.* ".$setup_dir."/".$dir_video;
	if ($put_scr==true) echo $command;
	exec($command,$oute);
	if ($put_scr==true) print_r($oute);
	if ($put_scr==true) echo("<br><br>");

	// encode with mpeg in order to make the video smaller in mb
	$command = "mencoder ".$setup_dir."/".$dir_video."video_vob.vob -o ".$setup_dir."/".$dir_video."video_encoded.mpeg -ovc lavc -ofps 90 -mpegopts format=mpeg2:tsaf:vbitrate=8000 -nosound";
	if ($put_scr==true) echo($command."<br>");
//echo($command."<br>");
	if ($put_scr==true) echo("<br>converting the file video...");
	exec($command);
	//echo("done.<br>");
	//echo("<br> your file is here: http://".$ip_addr[0]."/test/video/".$prefix_dir."/".$dir_video."_video.mpeg");

	$command = "rm ".$setup_dir."/".$dir_video."video_vob.vob";
	if ($put_scr==true) echo $command;
	exec($command, $outy);
	if ($put_scr==true) print_r($outy);


}



function create_collage($put_scr, $me, $dir_tmp, $prefix_dir, $dir_check, $new_face, $new_face_present, $photos_for_recognizer_x, $photos_for_recognizer_y, $dir_final, $do_check_images, $polaroid_var, $setup_scale_factor){

//$theData = load_tabbed_file($myFile,false);
//echo($theData);
$nmb_images_output = 0;

//echo("<br>");
if ($put_scr==true) echo("<br>I am creating ".count($new_face)." images for the video....");

	$temp_4_collage = $dir_tmp."/".$me['id']."_temp_4_collage.jpg";
	print_r($new_face);

// for all images..
for($kk=0;$kk<count((array)$new_face);$kk++){

	// initial size of the black image
	$size[0] = 800;
	$size[1] = 600; 
	echo("first");

	// if it is the first image, it is black, otherwise it is the previous computed image.
	if($kk==0){
	$baseline = @imagecreatetruecolor($size[0], $size[1]) or die("Cannot Initialize new GD image stream");
	}
	else{
	$baseline = @imagecreatefromjpeg($temp_4_collage);
	}
	echo("   second");
	


	echo($new_face[$kk]);
	echo(isset($new_face[$kk]));
	// check if the face is really present
	if (isset($new_face[$kk])){
		//echo("ciao");
		echo("   terzo");
		$tmp_size = getimagesize($new_face[$kk][0]);
		$add_pixel[0] = 0.3*$tmp_size[0];
		$add_pixel[1] = 0.3*$tmp_size[1];
	
		$border_x = 0;
		$border_y = 0;
	  
		echo($kk);
		echo("  quattro");
	  
		if($new_face_present[$kk]>0){
	
			if ($put_scr==true) echo("<br><br><br>I am creating the collage for the image number ".$new_face[$kk][0]);
		
			
			$size_original = getimagesize($new_face[$kk][0]);


			//
			// add white border - doe NOT work properly now.
			//
			if ($polaroid_var==true){
			
				$border_x = 10;
				$border_y = 10;
			
				//crop in order to add later the white border of the polaroid image
				$exec_string_srt = "convert -crop ".($size_original[0]-2*$border_x)."x".($size_original[1]-2*$border_y)."+".$border_x."+".$border_y." +repage ".$new_face[$kk][0]." ".$new_face[$kk][0];
				echo($exec_string_srt);
				exec($exec_string_srt);
			
				$exec_string_srt = "convert -border ".($size_original[0]-2*$border_x)."x".($size_original[1]-2*$border_y)." -bordercolor white ".$new_face[$kk][0]." ".$new_face[$kk][0].".png";
				//echo $exec_string_srt;
				exec($exec_string_srt);
	
			/*
				$exec_string_srt = "convert -bordercolor white -background black -border ".$border_x."x".$border_y." -polaroid 0 ".$new_face[$kk][0]." ".$new_face[$kk][0].".png";
				//echo($exec_string_srt);
				exec($exec_string_srt);
			*/
				$exec_string_srt = "convert -border ".$add_pixel[0]."x".$add_pixel[1]." -bordercolor transparent ".$new_face[$kk][0].".png ".$new_face[$kk][0].".png";
				//echo $exec_string_srt;
				exec($exec_string_srt);
			
				
				echo("sono in polaroid");
				
			
			}
			else{


				//
				// add transparent border
				//
				$exec_string_srt = "convert -border ".$add_pixel[0]."x".$add_pixel[1]." -bordercolor transparent ".$new_face[$kk][0]." ".$new_face[$kk][0].".png";
				//echo $exec_string_srt;
				exec($exec_string_srt);
			}	

			$im = @imagecreatefrompng($new_face[$kk][0].".png");
		
			
		
			$theta = 0; //$new_face[$kk][7];
		
			$wmSize[0]= imagesx($im);
			$wmSize[1]= imagesy($im);
			//echo("<br>");
			//echo $wmSize[0];
			//echo("<br>");
			//echo $wmSize[1];
		

		if ($do_check_images){
	
		  //
		  // draw circle to show the point detected
		  //
		  $col_ellipse = imagecolorallocate($im, 255, 0, 0);
		  $col_ellipse2 = imagecolorallocate($im, 255, 0, 255);
		  //if ($put_scr==true) echo("<br> face center perc".$face_center[$kk]['x']);
		  if ($put_scr==true) echo("<br> face center pixel".$new_face[$kk][1]*$wmSize[0]/100);
		  imagefilledellipse($im, $new_face[$kk][1]*($tmp_size[0])/100 + $add_pixel[0], $new_face[$kk][2]*($tmp_size[1])/100 + $add_pixel[1], 10, 10, $col_ellipse);
		  imagefilledellipse($im, $new_face[$kk][3]*($tmp_size[0])/100 + $add_pixel[0], $new_face[$kk][4]*($tmp_size[1])/100 + $add_pixel[1], 10, 10, $col_ellipse);
		  imagefilledellipse($im, $new_face[$kk][5]*($tmp_size[0])/100 + $add_pixel[0], $new_face[$kk][6]*($tmp_size[1])/100 + $add_pixel[1], 10, 10, $col_ellipse);
	
		  imagefilledellipse($im, $photos_for_recognizer_x[$kk]*($tmp_size[0])/100 + $add_pixel[0], $photos_for_recognizer_x[$kk]*($tmp_size[1])/100 + $add_pixel[1], 10, 10, $col_ellipse2);
	
		  $numpad=number_pad($kk,4);
		  $f_name = $dir_check."tmp_to_check_myself".$numpad.".jpg";
		  imagejpeg($im, $f_name);
	
	
		}  // end if ($do_check_images==true)



	
	$scaling_factor = (double)$setup_scale_factor/$new_face[$kk][9];

	//$scaling_factor = (double)(($new_face[$kk][5]*$new_face[$kk][6])*$percentage_area_face)/(15*($size[0]*$size[1]));
	//$scaling_factor = (double)(($size[0]*$size[1])/(55*);

	if ($put_scr==true) echo("<br> scaling factor".$scaling_factor."</br>");


	$nWidth = round($wmSize[0]*$scaling_factor,0);
	if($size[0]>$size[1]){
		$nHeight = round(($nWidth* $wmSize[1] / $wmSize[0]),0);
	}
	else{
		$nHeight = round(($nWidth* $wmSize[0] / $wmSize[1]),0);
	}


	//echo $nWidth. " - ".$nHeight;


	//echo $new_face[$kk][9];

	
	$coordinate_x = $new_face[$kk][1]*($tmp_size[0])/100 + $add_pixel[0] + $border_x; //$new_face[$kk][11]+$add_pixel;
	$coordinate_y = $new_face[$kk][2]*($tmp_size[1])/100 + $add_pixel[1] + $border_y; //$new_face[$kk][12]+$add_pixel;



	$theta = $new_face[$kk][7];

	$exec_string_srt = "convert ".$new_face[$kk][0].".png -matte -virtual-pixel transparent -distort ScaleRotateTranslate '".$coordinate_x.",".$coordinate_y." ".$scaling_factor.",".$scaling_factor." ".-1*$theta."' ".$new_face[$kk][0]."_rotate.png";
//$exec_string_srt = "convert ".$new_face[$kk][0].".png -matte -virtual-pixel transparent -distort ScaleRotateTranslate '".$coordinate_x.",".$coordinate_y." 1,1 ".-1*$theta."' ".$new_face[$kk][0]."_rotate.png";
	if ($put_scr==true) echo $exec_string_srt;
	exec($exec_string_srt);
	if ($put_scr==true) echo("<br>");

        $exec_string_srt = "rm ".$new_face[$kk][0].".png";
	if ($put_scr==true) echo $exec_string_srt;
	exec($exec_string_srt);


	$im = @imagecreatefrompng($new_face[$kk][0]."_rotate.png");
	//imagepng($im);

$nWidth = imagesx($im);
$nHeight = imagesy($im);

	$newImg = imagecreatetruecolor($nWidth, $nHeight);
	if ($put_scr==true) echo("nWidth is ".$nWidth." and nHeight is ".$nHeight);
	imagealphablending($newImg, false);
	imagesavealpha($newImg,true);


	$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
	imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
	imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $wmSize[0], $wmSize[1]);


	$image = imagecreatetruecolor($size[0], $size[1]);


	$myself_center_x = $size[0]/2;
	$myself_center_y = $size[1]/2;

	$percentage_x = $new_face[$kk][1];
	$percentage_y = $new_face[$kk][2];
	//echo($percentage_x);

	//echo $size_original[1];
	//echo $size_original[0];

	

	$position_x = $myself_center_x - ($coordinate_x);  // $position_x = $myself_center_x - ($position_me_photo_x);
	$position_y = $myself_center_y - ($coordinate_y);  // $position_y = $myself_center_y - ($position_me_photo_y);



	imagecopyresampled($image, $baseline, 0, 0, 0, 0, $size[0], $size[1], imagesx($baseline), imagesy($baseline));   
	imagealphablending($image,true); 
	imagecopy($image, $newImg, $position_x, $position_y, 0, 0,  imagesx($newImg),  imagesy($newImg));


	//imagejpeg($image);

	imagejpeg($image, $temp_4_collage);
	$numpad=number_pad($kk,4);
	imagejpeg($image,$dir_final."collage_".$numpad.".jpg");
	imagedestroy($image);
	$nmb_images_output++;

	} //end if($new_face_present[$opp]>0){

}

} //for($kk=0;$kk<count($new_face);$kk++){
	//$rv[0] = $number_faces_checked;
	//$rv[1] = $nmb_images_output;

$exec_string_srt = "rm ".$temp_4_collage;
if ($put_scr==true) echo $exec_string_srt;
exec($exec_string_srt);
      
}

$end_time_today = date("Ymd");
$end_time_time = date("His");
$end_overall_duration = compute_time();

?>
